<template>
  <view class="user-list">
    <!-- 空状态 -->
    <view v-if="mutualList.length === 0 && !loading" class="empty-state">
      <u-icon name="heart" size="60" color="#ccc"/>
      <text class="empty-text">暂无互相关注的好友</text>
      <view class="find-friends-btn-container">
        <up-button
            text="发现好友"
            size="mini"
            type="primary"
            color="#95EC69"
            @click="findFriends"
        ></up-button>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-else-if="loading" class="loading-state">
      <u-loading-icon mode="flower" color="#36BFFA" size="40"/>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 列表内容 -->
    <view v-else class="list-content">
      <view v-for="user in mutualList" :key="user.userId" class="user-card">
        <UserListItem
            :user="user"
            @follow="handleFollow"
            @unfollow="handleUnfollow"
        />
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore" class="load-more">
        <u-loading-icon mode="flower" color="#36BFFA" size="30"/>
        <text class="load-more-text">加载更多...</text>
      </view>

      <!-- 没有更多 -->
      <view v-else-if="mutualList.length > 0 && !hasMore" class="no-more">
        <text>—— 没有更多了 ——</text>
        <view class="find-friends-btn-container">
          <up-button
              text="发现好友"
              size="mini"
              type="primary"
              color="#95EC69"
              @click="findFriends"
          ></up-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {ref, onMounted, watch} from 'vue';
import UserListItem from '../UserListItem/UserListItem.vue';
import {getMutualFollowList} from '../../apis/userSocialAPI';

// 接收用户ID
const props = defineProps({
  userId: {
    type: String,
    required: true
  }
});

// 发出刷新事件
const emits = defineEmits(['refresh']);

// 数据状态
const mutualList = ref([]);
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = ref(10);

onMounted(() => {
  loadMutualList();
});

// 监听userId变化，重新加载数据
watch(() => props.userId, () => {
  resetAndLoad();
});

// 加载互关列表
const loadMutualList = async () => {
  if (loading.value || !hasMore.value) return;

  loading.value = true;

  try {
    const res = await getMutualFollowList(props.userId, page.value, pageSize.value);

    if (res.statusCode === 200 && res.data.code === 200) {
      if (page.value === 1) {
        mutualList.value = res.data.data.records;
      } else {
        mutualList.value = [...mutualList.value, ...res.data.data.records];
      }

      // 判断是否还有更多数据
      hasMore.value = res.data.data.records.length >= pageSize.value;
      page.value++;
    } else {
      console.error('获取互关列表失败:', userResponse);
      throw new Error('获取互关列表失败');
    }
  } catch (error) {
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 下拉刷新
const onRefresh = () => {
  resetAndLoad();
  emits('refresh');
};

// 重置并重新加载
const resetAndLoad = () => {
  page.value = 1;
  hasMore.value = true;
  loadMutualList();
};

// 关注用户
const handleFollow = (targetUserId) => {
  // 模拟关注API请求
  simulateFollowApi(targetUserId).then(() => {
    // 更新本地数据状态
    const index = mutualList.value.findIndex(user => user.userId === targetUserId);
    if (index !== -1) {
      mutualList.value[index].isFollowed = true;
    }
    uni.showToast({
      title: '关注成功',
      icon: 'none'
    });
  });
};

// 取消关注
const handleUnfollow = (targetUserId) => {
  // 模拟取消关注API请求
  simulateUnfollowApi(targetUserId).then(() => {
    // 更新本地数据状态
    const index = mutualList.value.findIndex(user => user.userId === targetUserId);
    if (index !== -1) {
      mutualList.value = mutualList.value.filter(user => user.userId !== targetUserId);
    }
    // 更新粉丝列表状态
    const fanList = uni.getStorageSync('fanList') || [];
    const fanIndex = fanList.findIndex(user => user.userId === targetUserId);
    if (fanIndex !== -1) {
      fanList[fanIndex].isFollowed = false;
      fanList[fanIndex].isMutual = false;
      uni.setStorageSync('fanList', fanList);
    }
    uni.showToast({
      title: '已取消关注',
      icon: 'none'
    });
  });
};

// 发现好友
const findFriends = () => {
  uni.navigateTo({
    url: '/pages/find-friend/find-friend'
  });
};

// 模拟关注API
const simulateFollowApi = (userId) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(), 500);
  });
};

// 模拟取消关注API
const simulateUnfollowApi = (userId) => {
  return new Promise((resolve) => {
    setTimeout(() => resolve(), 500);
  });
};
</script>

<style lang="scss" scoped>
.user-list {
  padding: 10rpx;

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 600rpx;
    color: #999;

    .empty-text {
      margin-top: 20rpx;
      margin-bottom: 10rpx;
      font-size: 26rpx;
    }
  }

  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100rpx;
    color: #999;

    .loading-text {
      margin-top: 10rpx;
      font-size: 24rpx;
    }
  }

  .list-content {
    .user-card {
      margin-bottom: 15rpx;
    }

    .load-more, .no-more {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 20rpx 0;
      color: #999;
      font-size: 24rpx;
    }

    .load-more-text {
      margin-left: 10rpx;
    }

    .find-friends-btn-container {
      margin-top: 20rpx; // 与上方内容保持间距
      display: flex;
      justify-content: center; // 水平居中
    }
  }
}
</style>